class_name Player
extends Area2D

const ARROW_OFFSET := 5

@export var stats: CharacterStats : set = set_character_stats

@export var sprite_2d: Sprite2D
@export var stats_ui: StatsUI
@export var arrow: Sprite2D
@export var move_range:int
@export var cur_cell:Vector2i

@onready var targets: Array[Node] = []

func _ready() -> void:
	arrow.hide()

func set_character_stats(value: CharacterStats) -> void:
	stats = value
	
	if not stats.stats_changed.is_connected(update_stats):
		stats.stats_changed.connect(update_stats)
		
	update_player()
	
func update_player() -> void:
	if not stats is CharacterStats:
		return
	if not is_inside_tree():
		await ready
	
	sprite_2d.texture = stats.art
	arrow.position = Vector2.RIGHT * (sprite_2d.get_rect().size.x/2 + ARROW_OFFSET)
	update_stats()
	
func update_stats() -> void:
	stats_ui.update_stats(stats)

func take_damage(damage: int) -> void:
	if stats.health <= 0:
		return
	stats.take_damage(damage)
	
	if stats.health <= 0:
		queue_free()
		
func _on_area_entered(_area: Area2D) -> void:
	arrow.show()


func _on_area_exited(_area: Area2D) -> void:
	arrow.hide()
